import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { type PermissionFormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h, toRaw } from "vue";

export function usePermissionMgmt() {
  const form = reactive({
    name: "",
    code: "",
    type: "",
    status: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "权限编号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "权限名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "权限标识",
      prop: "code",
      minWidth: 150
    },
    {
      label: "权限类型",
      prop: "type",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={
            row.type === 1 ? "primary" : row.type === 2 ? "success" : "warning"
          }
          effect="plain"
        >
          {row.type === 1
            ? "菜单权限"
            : row.type === 2
            ? "按钮权限"
            : "数据权限"}
        </el-tag>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.status === 1 ? "success" : "danger"}
          effect="plain"
        >
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "描述",
      prop: "description",
      minWidth: 200
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function onSearch() {
    loading.value = true;
    // 模拟请求延时
    setTimeout(() => {
      const result = getPermissionList(toRaw(form), pagination);
      dataList.value = result.list;
      pagination.total = result.total;
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function openDialog(title = "新增", row?: PermissionFormItemProps) {
    addDialog({
      title: `${title}权限`,
      props: {
        formInline: {
          id: row?.id ?? null,
          name: row?.name ?? "",
          code: row?.code ?? "",
          type: row?.type ?? 1,
          status: row?.status ?? 1,
          description: row?.description ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as PermissionFormItemProps;
        function chores() {
          message(`您${title}了权限名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 实际开发先调用相应接口，再进行下面操作
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除权限名称为"${row.name}"的这条数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        console.log("删除权限", row);
        // 实际开发先调用删除接口，再进行下面操作
        message(`您删除了权限名称为${row.name}的这条数据`, { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  /** 权限列表 */
  function getPermissionList(params: any, pagination: PaginationProps) {
    // 模拟数据，实际开发中替换为真实的API调用
    const allData = [
      {
        id: 1,
        name: "用户查询",
        code: "system:user:query",
        type: 2,
        status: 1,
        description: "用户管理-查询权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 2,
        name: "用户新增",
        code: "system:user:add",
        type: 2,
        status: 1,
        description: "用户管理-新增权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 3,
        name: "用户修改",
        code: "system:user:edit",
        type: 2,
        status: 1,
        description: "用户管理-修改权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 4,
        name: "用户删除",
        code: "system:user:delete",
        type: 2,
        status: 1,
        description: "用户管理-删除权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 5,
        name: "角色查询",
        code: "system:role:query",
        type: 2,
        status: 1,
        description: "角色管理-查询权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 6,
        name: "角色新增",
        code: "system:role:add",
        type: 2,
        status: 1,
        description: "角色管理-新增权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 7,
        name: "角色修改",
        code: "system:role:edit",
        type: 2,
        status: 1,
        description: "角色管理-修改权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 8,
        name: "角色删除",
        code: "system:role:delete",
        type: 2,
        status: 1,
        description: "角色管理-删除权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 9,
        name: "菜单管理",
        code: "system:menu:list",
        type: 1,
        status: 1,
        description: "菜单管理-访问权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 10,
        name: "菜单查询",
        code: "system:menu:query",
        type: 2,
        status: 1,
        description: "菜单管理-查询权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 11,
        name: "菜单新增",
        code: "system:menu:add",
        type: 2,
        status: 1,
        description: "菜单管理-新增权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 12,
        name: "菜单修改",
        code: "system:menu:edit",
        type: 2,
        status: 1,
        description: "菜单管理-修改权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 13,
        name: "菜单删除",
        code: "system:menu:delete",
        type: 2,
        status: 1,
        description: "菜单管理-删除权限",
        createTime: new Date("2023-01-01")
      },
      {
        id: 14,
        name: "部门数据权限",
        code: "system:dept:data",
        type: 3,
        status: 1,
        description: "部门数据权限-仅查看本部门数据",
        createTime: new Date("2023-01-01")
      },
      {
        id: 15,
        name: "全局数据权限",
        code: "system:all:data",
        type: 3,
        status: 1,
        description: "全局数据权限-查看所有数据",
        createTime: new Date("2023-01-01")
      }
    ];

    // 简单的过滤逻辑
    let filteredData = allData;
    if (params.name) {
      filteredData = filteredData.filter(item =>
        item.name.includes(params.name)
      );
    }
    if (params.code) {
      filteredData = filteredData.filter(item =>
        item.code.includes(params.code)
      );
    }
    if (params.type !== "") {
      filteredData = filteredData.filter(item => item.type === params.type);
    }
    if (params.status !== "") {
      filteredData = filteredData.filter(item => item.status === params.status);
    }

    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    const list = filteredData.slice(start, end);

    return {
      list,
      total: filteredData.length
    };
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange
  };
}
